import 'package:flutter/material.dart';
import 'package:flutter_demo/core/common/api/search_api.dart';
import 'package:flutter_demo/core/common/values/server.dart';
import 'package:flutter_demo/ui/pages/search/mudule/query_search_page.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

import 'index.dart';

class SearchController extends GetxController {
  SearchController();

  final state = SearchState();
  late RefreshController refreshController;
  // tap
  void handleTap(int index) {
    Get.snackbar(
      "标题",
      "消息",
    );
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.editingController = TextEditingController();
    refreshController = RefreshController();

    final arguments = Get.arguments;
    logger.i(arguments);
    state.editingController.text = arguments["keywords"];
    state.keywords = arguments["keywords"];
    state.channel = arguments["channel"];

    // state.editingController.addListener(() {
    //   state.keywords = state.editingController.text;
    // });
    query(1);
    hideKeyboard();
  }

  void hideKeyboard() {
    state.focusNode.unfocus();
  }

  query(int pageNo) async {
    QuerySearchPageVO value = await SearchApi.querySearchPage(
        pageNo: pageNo.toString(),
        keyWord: state.keywords,
        channel: state.channel);
    //加载中状态
    state.status.value = "1";
    update();
    if (state.vo != null && state.vo?.answerList != null && pageNo != 1) {
      state.vo?.answerList!.addAll(value.answerList!);
    } else {
      state.vo = value;
    }
    //加载完成状态
    state.status.value = "4";
    update();
  }

  //点击搜索按钮
  void onSearchPage(String keywords) async {
    hideKeyboard();
    state.page = 1;
    if (keywords != state.keywords) {
      logger.i(keywords);
      logger.i(state.keywords);
      state.keywords = keywords;
      //搜索按钮触发
      state.channel = '1';
    }

    await query(state.page);
  }

  //下拉加载更多
  void onMorePage() async {
    await query(state.page + 1);
    state.page += 1;

    if (state.page >= int.parse(state.vo?.totalPage as String)) {
      //最后一页
      refreshController.loadNoData();
    } else {
      refreshController.loadComplete();
    }
  }

  //上拉刷新
  void onRefreshPage() async {
    state.page = 1;
    await query(state.page);
    //去掉刷新按钮和，下拉完成不能重用。 只可用于上拉。
    refreshController.refreshCompleted();

    refreshController.resetNoData();
  }
}
